/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.losalpes.jms;

import com.losalpes.applications.IVentasServices;
import com.losalpes.persistence.entity.Promocion;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;

/**
 *
 * @author LUIS
 */
@MessageDriven(mappedName = "jms/PromocionTopic", activationConfig = {
    @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
    @ActivationConfigProperty(propertyName = "subscriptionDurability", propertyValue = "Durable"),
    @ActivationConfigProperty(propertyName = "clientId", propertyValue = "VentasMessageBean"),
    @ActivationConfigProperty(propertyName = "subscriptionName", propertyValue = "VentasMessageBean")
})
public class VentasMessageBean implements MessageListener {

    @Resource
    MessageDrivenContext mdc;
    @EJB
    IVentasServices ventasService;

    public VentasMessageBean() {
    }

    /**
     * Procesa la lectura del mensaje por parte de la aplicaciòn de ventas
     * @param message mensaje recibido
     */
    public void onMessage(Message message) {
        ObjectMessage msg = null;
        try {
            if (message instanceof ObjectMessage) {
                msg = (ObjectMessage) message;
                ventasService.procesarPromocion((Promocion) msg.getObject());

            } else {
                Logger.getLogger(VentasMessageBean.class.getName()).log(Level.SEVERE,
                        "Mensaje de tipo equivocado: " + message.getClass().getName());
            }
        } catch (JMSException e) {
            e.printStackTrace();
            mdc.setRollbackOnly();
        } catch (Throwable te) {
            te.printStackTrace();
        }
    }
}
